﻿using Arcthitectrue.Common;
using B.Auth.APi.Application.Command.Users;
using B.Auth.APi.Application.Command.Users.Dtos;
using B.Auth.Domain.Entity;
using B.Auth.Domain.Repository;
using B.Auth.Enum;
using MD5Hash;
using MediatR;

namespace B.Auth.APi.Application.CommandHand
{
    public class LoginCommandHand : IRequestHandler<LoginCommand, ApiResult<LoginDto>>
    {

        private readonly IBaseRepository<User> _user;
        private readonly IBaseRepository<DepartmentModel> _depaer;
        private readonly JwtTools _jwtTools;
        private readonly IConfiguration _configuration;


        public LoginCommandHand(IBaseRepository<User> user, IBaseRepository<DepartmentModel> depaer, JwtTools jwtTools, IConfiguration configuration)
        {
            _user = user;
            _depaer = depaer;
            _jwtTools = jwtTools;
            _configuration = configuration;
        }

        public Task<ApiResult<LoginDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {

            var result = new ApiResult<LoginDto>();
           
            
            var m = _user.GetAll().FirstOrDefault(x=>x.UserName==request.UserName);
            
            if (m != null)
            {
                var password = request.Password.GetMD5();
                if (m.PassWord == password)
                {


                    var token = _jwtTools.JwtNewString(_configuration, m.Id.ToString(),m.Name);

                    var dto = new LoginDto();
                    dto.UserName = request.UserName;
                    dto.Name = m.Name;
                    dto.departid = m.departid;
                    dto.DepartName = _depaer.GetAll().FirstOrDefault(x => x.Departid == dto.departid)?.DepartName ?? "";
                    dto.id = m.Id;
                    result.Code=ApiEnum.ok;
                    result.Message = token;
                    result.data = dto;
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code=ApiEnum.fail;

                    result.Message = "用户名密码不匹配";
                   
                    
                   
                }

            }
            else
            {
                result.Code = ApiEnum.fail;
                result.Message = "用户名密码不匹配";
                return Task.FromResult(result);
                
            }
            return Task.FromResult(result);

        }
    }
}
